package com.yxr.affairs.widget;

import java.util.ArrayList;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;

import com.yxr.affairs.R;
import com.yxr.affairs.utils.DateUtils;
import com.yxr.affairs.utils.Utils;

public class MonthDateView extends View {

    /**
     * 列数
     */
    private static final int NUM_COLUMNS = 7;

    /**
     * 行数
     */
    private static final int NUM_ROWS = 6;
    private Paint mPaint, linePaint;

    /**
     * 默认日期颜色
     */
    private int mDayColor = Color.parseColor("#333333");

    /**
     * 当前日期的颜色
     */
    private int mCurrentColor = Color.parseColor("#fda52b");

    /**
     * 当前的年月日
     */
    private int mCurrYear, mCurrMonth, mCurrDay;

    /**
     * 选择的年月日
     */
    private int mSelYear, mSelMonth, mSelDay;

    /**
     * 列宽 行高
     */
    private int mColumnSize, mRowSize;

    /**
     * 获取屏幕信息
     */
    private DisplayMetrics mDisplayMetrics;

    /**
     * 日期字体大小
     */
    private int mDaySize = 14;

    private int [][] daysString;

    private DateClick dateClick;

    private ArrayList<String> daysHasThingList;

    private Bitmap mBitmap;

    public MonthDateView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mDisplayMetrics = getResources().getDisplayMetrics();
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        Calendar calendar = Calendar.getInstance();
        mCurrYear = calendar.get(Calendar.YEAR);
        mCurrMonth = calendar.get(Calendar.MONTH);
        mCurrDay = calendar.get(Calendar.DATE);

        setSelectYearMonth(mCurrYear, mCurrMonth, mCurrDay);

        mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.sign_icon);

        linePaint = new Paint();
        linePaint.setStyle(Style.STROKE);
        int lineColor = Color.parseColor("#eeeeee");
        linePaint.setColor(lineColor);
        int strokeWidth = 2;
        linePaint.setStrokeWidth(strokeWidth);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        initSize();
        daysString = new int[NUM_ROWS][NUM_COLUMNS];
//		mPaint.setTextSize(mDaySize * mDisplayMetrics.scaledDensity);
        mPaint.setTextSize(Utils.dp2px(getResources(), mDaySize));

        int mMonthDays = DateUtils.getMonthDays(mSelYear, mSelMonth);
        int weekNumber = DateUtils.getFirstDayWeek(mSelYear, mSelMonth);

        String dayString;
        String dayStr;
        for(int day = 0; day < mMonthDays; day++){
            dayString = String.valueOf((day + 1));

            int column = (day + weekNumber - 1) % 7;
            int row = (day + weekNumber - 1) / 7;

            daysString[row][column] = day + 1;

            if (daysString[row][column] < 10) {
                dayStr = "0" + dayString;
            }else {
                dayStr = dayString;
            }

            int startX = (int) (mColumnSize * column + (mColumnSize - mPaint.measureText(dayStr)) / 2);
            int startY = (int) (mRowSize * row + (mRowSize - mPaint.ascent() ) / 2);
//			int startY = (int) (mRowSize * row + mRowSize / 2 - (mPaint.ascent() + mPaint.descent()) / 2);

            int startRecX = mColumnSize * column;
            int startRecY = mRowSize * row;
            int endRecX = startRecX + mColumnSize;
            int endRecY = startRecY + mRowSize;
            drawCircle(dayStr, canvas, startRecX, startRecY, endRecX, endRecY);

//			dayString.equals(String.valueOf(mSelDay)

            if(dayString.equals(mCurrDay + "") && mCurrMonth == mSelMonth){
                mPaint.setColor(mCurrentColor);
            }else{
                mPaint.setColor(mDayColor);
            }

            canvas.drawText(dayStr, startX, startY, mPaint);

//			tv_date.setText(mSelYear + "年" + (mSelMonth + 1) + "月");
        }

        for (int i = 1; i < 6; i++) {
            canvas.drawLine(0, mRowSize * i + 4, getWidth(), mRowSize * i + 4, linePaint);
        }
    }

    private void drawCircle(String dayStr, Canvas canvas, int startRecX,
                            int startRecY, int endRecX, int endRecY){

        if(daysHasThingList != null && daysHasThingList.size() > 0){
            if(!daysHasThingList.contains(dayStr)){
                return;
            }

            Rect mSrcRect = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
            Rect mDestRect = new Rect(startRecX, startRecY, endRecX, endRecY);
            canvas.drawBitmap(mBitmap, mSrcRect, mDestRect, mPaint);
        }
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    private int downX = 0, downY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int eventCode=  event.getAction();
        switch(eventCode){
            case MotionEvent.ACTION_DOWN:
                downX = (int) event.getX();
                downY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                int upX = (int) event.getX();
                int upY = (int) event.getY();
                if(Math.abs(upX - downX) < 10 && Math.abs(upY - downY) < 10){
                    performClick();
                    doClickAction((upX + downX)/2, (upY + downY)/2);
                }
                break;
        }
        return true;
    }

    private void initSize(){
        mColumnSize = getWidth() / NUM_COLUMNS;
        mRowSize = getHeight() / NUM_ROWS;
    }

    private void setSelectYearMonth(int year,int month,int day){
        mSelYear = year;
        mSelMonth = month;
        mSelDay = day;
    }

    private void doClickAction(int x, int y){
        int row = y / mRowSize;
        int column = x / mColumnSize;
        setSelectYearMonth(mSelYear, mSelMonth, daysString[row][column]);
        invalidate();
        if(dateClick != null){
            dateClick.onClickOnDate();
        }
    }

    /**
     * 左点击，日历向后翻页
     */
    public void onLeftClick(){
        int year = mSelYear;
        int month = mSelMonth;
        int day = mSelDay;
        if(month == 0){//若果是1月份，则变成12月份
            year = mSelYear - 1;
            month = 11;
        }else if(DateUtils.getMonthDays(year, month) == day){
            //如果当前日期为该月最后一天，当向前推的时候，就需要改变选中的日期
            month = month - 1;
            day = DateUtils.getMonthDays(year, month);
        }else{
            month = month - 1;
        }
        setSelectYearMonth(year, month, day);
        invalidate();
    }

    /**
     * 右点击，日历向前翻页
     */
    public void onRightClick(){
        int year = mSelYear;
        int month = mSelMonth;
        int day = mSelDay;
        if(month == 11){//若果是12月份，则变成1月份
            year = mSelYear + 1;
            month = 0;
        }else if(DateUtils.getMonthDays(year, month) == day){
            //如果当前日期为该月最后一天，当向前推的时候，就需要改变选中的日期
            month = month + 1;
            day = DateUtils.getMonthDays(year, month);
        }else{
            month = month + 1;
        }
        setSelectYearMonth(year,month,day);
        invalidate();
    }

    /**
     * 获取选择的年份
     *
     * @return
     */
    public int getmSelYear() {
        return mSelYear;
    }
    /**
     * 获取选择的月份
     *
     * @return
     */
    public int getmSelMonth() {
        return mSelMonth;
    }

    /**
     * 获取选择的日期
     *
     */
    public int getmSelDay() {
        return this.mSelDay;
    }

    public void setDaysHasThingList(ArrayList<String> daysHasThingList) {
        this.daysHasThingList = daysHasThingList;
        invalidate();
    }

    public interface DateClick{
        public void onClickOnDate();
    }

    public void setDateClick(DateClick dateClick) {
        this.dateClick = dateClick;
    }

    /**
     * 跳转至今天
     */
    public void setTodayToView(){
        setSelectYearMonth(mCurrYear, mCurrMonth, mCurrDay);
        invalidate();
    }
}
